﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using BestTrader.Cms.Admin.Models;
using BestTrader.Cms.IServices;
using BestTrader.Cms.ViewModels;
using BestTrader.Cms.Core.Helper;
using BestTrader.Cms.Admin.Validation;
using FluentValidation.Results;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using AutoMapper;

namespace BestTrader.Cms.Admin.Controllers
{
    [Authorize]
    public class HomeController : BaseController
    {
        #region Init
        public String UserId { get { return User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value; } }
        public String RoleId { get { return User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value; } }
        public String RealName { get { return User.Claims.FirstOrDefault(x => x.Type == "RealName")?.Value; } }

        private readonly IHistory_DealedOrderReportService _historyOrderService;
        private readonly IRebateRecordService _rebateRecordService;
        private readonly IManagerService _managerService;
        private readonly IMapper _mapper;

        public HomeController(IHistory_DealedOrderReportService historyOrderService
            , IRebateRecordService rebateRecordService
            , IManagerService managerService
            , IMapper mapper)
        {
            this._historyOrderService = historyOrderService;
            this._rebateRecordService = rebateRecordService;
            this._managerService = managerService;
            this._mapper = mapper;
        } 
        #endregion

        /// <summary>
        /// 主界面
        /// </summary>
        public IActionResult Index()
        {
            ViewData["RealName"] = RealName;
            TempData["RoleId"] = RoleId;

            //var m = new Cms.Models.Manager();
            //var c = _mapper.Map<RmmfSoftServices.Models.CustomerInput>(m);
            return View();
        }

        /// <summary>
        /// 控制中心
        /// </summary>
        public IActionResult Main()
        {
            ViewData["LoginCount"] = User.Claims.FirstOrDefault(x => x.Type == "LoginCount")?.Value;
            ViewData["LoginLastIp"] = User.Claims.FirstOrDefault(x => x.Type == "LoginLastIp")?.Value;
            ViewData["LoginLastTime"] = User.Claims.FirstOrDefault(x => x.Type == "LoginLastTime")?.Value;
            ViewData["AgentManagers"] = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(UserId, RoleId, true);
            TempData["RoleId"] = RoleId;

            return View();
        }

        public string DataStatistics([FromQuery]MainRequestModel item) {
            var result = new TableDataResult<MainDataStatisticsModel>();
            MainValidation validationRules = new MainValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                var _managerId = item.ManagerId;
                var _start = item.StartDate.Value;
                var _end = item.EndDate.Value.Date.AddDays(1).AddSeconds(-1);
                ///1 是结算日
                if ( item.SearchDateType == "1")
                {
                    _start = item.StartDate.Value.AddHours(6);
                    _end = item.EndDate.Value.Date.AddDays(1).AddHours(6).AddSeconds(-1);
                }
                result.Data = new MainDataStatisticsModel {
                    DealedOrder = _historyOrderService.GetDealedOrderReportByAgentId(_managerId, _start, _end),
                    Rebate = _rebateRecordService.GetRebateRecordByAgentId(_managerId, _start, _end,UserId,RoleId),
                };
               
                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
